package ar.com.age.distribuidora.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.age.distribuidora.dao.LoteDeCompraDao;
import ar.com.age.distribuidora.dominio.LoteDeCompra;

@Component
public class LoteDeCompraHibernateDao implements LoteDeCompraDao {

	private SessionFactory sessionFactory;

	@Autowired(required = true)
	public void setSessionFactory(SessionFactory factory) {
		this.sessionFactory = factory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public LoteDeCompra saveOrUpdate(LoteDeCompra loteDeCompra) {
		if (loteDeCompra.getId() == null) {
			getCurrentSession().save(loteDeCompra);
		} else {
			getCurrentSession().update(loteDeCompra);
		}
		return loteDeCompra;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoteDeCompra> getAll() {
		Query query = getCurrentSession().createQuery(
				"from " + LoteDeCompra.class.getName());
		return query.list();
	}

	@Override
	public void physicalDelete(LoteDeCompra lote){
		
		getCurrentSession().delete(lote);
				
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<LoteDeCompra> find(String codigo, String estado, Date desde, Date hasta, String producto){
		
		List<LoteDeCompra> lotes = null;
		Criteria criteria = getCurrentSession().createCriteria(LoteDeCompra.class);
		
		if(codigo != "")
			criteria.add(Restrictions.like("codigo", "%"+codigo+"%"));
		if(estado != "")
			criteria.add(Restrictions.like("estado", "%"+estado+"%"));
		if(desde != null)
			criteria.add(Restrictions.ge("fechaVencimiento", desde));
		if(hasta != null)
			criteria.add(Restrictions.le("fechaVencimiento", hasta));
		if(producto != "")
			criteria.createCriteria("producto", "producto").add(Restrictions.like("nombre", "%"+producto+"%"));
		
		lotes = criteria.list();
		
		return lotes;
	}
}
